<?php

namespace app\admin\controller;

use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;

class NewsController extends AdminBase
{
    public function lists() {
        if ($this->request->isAjax()) {
            $keyword=input('post.key');
            $type=input('post.type');
            $pageSize = $this->getPageSize();
            $where = [];
            $keyword && $where[] = ['title', 'like', "%$keyword%"];
            $data = Db::name('news')
                ->where($where)
                ->order('id desc')
                ->paginate($pageSize);
            $total = $data->total();
            $list = $data->items();
            foreach ($list as $key => $v) {
                if($v['status'] == -1 || $v['status'] == 2){
                    $btnInfo = \tpflow\Api::wfAccess('status', ['id' => $v['id'], 'type' => 'news', 'status' => $v['status']]);
                }else{
                    $btnInfo = \tpflow\Api::wfAccess('btn', ['id' => $v['id'], 'type' => 'news', 'status' => $v['status']]);
                }
                $list[$key]['statusBtn'] = $btnInfo;
                $list[$key]['uptime'] = date('Y-m-d H:i:s', $v['uptime']);
            }
            return $this->listJson($list, $total);
        } else {
            return view();
        }
    }

    public function add() {
        if (Request::isAjax()) {
            $data = Request::post();
            $user = $this->app->user;
            $data['uid'] = $user['uid'];
            $data['uptime'] = time();
            $data['status'] = 0;
            $news = Db::name('news')->save($data);
            if ($news) {
                return $this->okJson('success');
            } else {
                return $this->errJson('error');
            }
        } else {
            return view();
        }
    }

    public function edit() {
        if (Request::isAjax()) {
            $data = Request::post();
            $id = $data['id'];
            unset($data['id']);
            $data['uptime'] = date('Y-m-d H:i:s');
            $newsInfo = Db::name('news')->where('id', $id)->find();
            if($newsInfo['status'] == 0 || $newsInfo['status'] == -1) {
                $data['status'] = 0;
                $news = Db::name('news')->where('id', $id)->update($data);
                if ($news) {
                    return $this->okJson('success');
                } else {
                    return $this->errJson('error');
                }
            }else{
                return $this->errJson('流程审批中不能修改');
            }
        } else {
            $aid = input('id');
            $data = Db::name('news')->find($aid);
            View::assign('data', $data);
            return View::fetch();
        }
    }

    public function delete() {
        $id = input('id');
        Db::name('news')->delete($id);
    }

    public function view() {
        return view();
    }
}